package UF_IMAGEIO;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import java.io.IOException;

public class Example_02 {
    public boolean canDecodeInput(ImageInputStream stream) {
        byte[] b = new byte[8];
        try {
            final long l = stream.length();
            if (l > 655335) {
                return false;
            }
            stream.mark();
            stream.readFully(b);
            stream.reset();
        } catch (IOException e) {
            return false;
        }

        // Cast unsigned character constants prior to comparison
        return (b[0] == (byte) 'm' && b[1] == (byte) 'y' &&
                b[2] == (byte) 'f' && b[3] == (byte) 'o' &&
                b[4] == (byte) 'r' && b[5] == (byte) 'm' &&
                b[6] == (byte) 'a' && b[7] == (byte) 't');
    }

    public void decode(Object data) throws IOException {
        final ImageInputStream stream = ImageIO.createImageInputStream(data);
        try {
            if (canDecodeInput(stream)) {
                try {
                    final int[] colors = new int[(int) stream.length()];
                    for (int i = 0; i < colors.length; i++) {
                        colors[i] = stream.readInt();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } finally {
            stream.close();
        }
    }

}
